// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';

// FormData polyfill for mini-program environment
if (typeof FormData === 'undefined') {
	global.FormData = class FormData {
		constructor() {
			this._data = [];
		}
		
		append(key, value, filename) {
			this._data.push({
				key: key,
				value: value,
				filename: filename || null
			});
		}
		
		delete(key) {
			this._data = this._data.filter(item => item.key !== key);
		}
		
		get(key) {
			const item = this._data.find(item => item.key === key);
			return item ? item.value : null;
		}
		
		getAll(key) {
			return this._data.filter(item => item.key === key).map(item => item.value);
		}
		
		has(key) {
			return this._data.some(item => item.key === key);
		}
		
		set(key, value, filename) {
			this.delete(key);
			this.append(key, value, filename);
		}
		
		entries() {
			return this._data.map(item => [item.key, item.value]);
		}
		
		keys() {
			return this._data.map(item => item.key);
		}
		
		values() {
			return this._data.map(item => item.value);
		}
		
		[Symbol.iterator]() {
			return this.entries()[Symbol.iterator]();
		}
	};
}


/**
 * 发送请求
 */
function baseRequest(url, method, data, options = {}, params, prefix) {
	const { noAuth = false, noVerify = false } = options;
	let Url = HTTP_REQUEST_URL,header = HEADER
	if (params != undefined) {
		header = HEADERPARAMS;
	}
	// 如果是FormData，不设置Content-Type，让浏览器自动设置
	if (data instanceof FormData) {
		header = { ...header };
		delete header['content-type'];
	}
	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
		// 只有在需要认证时才添加token
		if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
	} else {
		// 不需要认证的请求，不添加token
		
	}
	return new Promise((reslove, reject) => {
		// 处理FormData
		let requestData = data || {};
		if (data instanceof FormData) {
			// 对于FormData，转换为普通对象格式
			console.log('检测到FormData，转换为普通对象格式');
			requestData = {};
			for (let [key, value] of data.entries()) {
				requestData[key] = value;
			}
		}
		
		uni.request({
			// url: Url + `${prefix?'/api/public/':'/api/front/'}` + url,
			url: Url + `${prefix?'/api/public/':'/api/front/'}` + url,
			method: method || 'GET',
			header: header,
			data: requestData,
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code == 200)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 401,402].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				}else if (res.data.code == 500){
					reject(res.data.message || '系统异常');
				}else if (res.data.code == 400){
					reject(res.data.message || '参数校验失败');
				}else if (res.data.code == 404){
					reject(res.data.message || '没有找到相关数据');
				}else if (res.data.code == 403){
					reject(res.data.message || '没有相关权限');
				} else
					reject(res.data.message || '系统错误');
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params,prefix) => baseRequest(api, method, data, opt || {}, params,prefix)
});



export default request;
